import json
import os
import logging  # 使用标准logging模块


class Config:
    """配置管理类"""

    def __init__(self, config_file="config.json"):
        """
        初始化配置

        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config = {}
        self.logger = logging.getLogger("config")

        # 加载配置
        self.load_config()

    def load_config(self):
        """加载配置文件"""
        try:
            if os.path.exists(self.config_file):
                with open(self.config_file, "r", encoding="utf-8") as f:
                    self.config = json.load(f)
                self.logger.info(f"已加载配置文件: {self.config_file}")
            else:
                self.logger.warning(
                    f"配置文件不存在: {self.config_file}，将使用默认配置"
                )
                self.config = self._get_default_config()
        except Exception as e:
            self.logger.error(f"加载配置文件失败: {str(e)}，将使用默认配置")
            self.config = self._get_default_config()

    def _get_default_config(self):
        """获取默认配置"""
        return {
            "service": {
                "name": "rongmei-media-service",
                "port": 5555,
                "host": "192.168.5.22",
            },
            "nacos": {
                "server_addr": "192.168.3.220:8848",
                "namespace": "public",
                "group": "DEFAULT_GROUP",
                "enabled": True,
                "metadata": {
                    "version": "1.0.0",
                    "preserved.register.source": "SPRING_CLOUD",
                },
            },
            "minio": {
                "endpoint": "127.0.0.1:9000",
                "access_key": "minioadmin",
                "secret_key": "minioadmin",
                "secure": False,
                "bucket": "rongmei-video-frames",
                "public_url": "http://127.0.0.1:9000",
            },
            "logging": {
                "level": "INFO",
                "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                "file": "logs/app.log",
            },
        }

    def get(self, key, default=None):
        """
        获取配置值

        Args:
            key: 配置键，支持点号分隔的多级键，如 "service.port"
            default: 默认值，如果配置不存在则返回此值

        Returns:
            配置值
        """
        # 处理多级键
        keys = key.split(".")
        value = self.config

        for k in keys:
            if isinstance(value, dict) and k in value:
                value = value[k]
            else:
                return default

        return value

    def set(self, key, value):
        """
        设置配置值

        Args:
            key: 配置键，支持点号分隔的多级键，如 "service.port"
            value: 配置值

        Returns:
            是否设置成功
        """
        # 处理多级键
        keys = key.split(".")
        config = self.config

        # 遍历除最后一个键外的所有键
        for i in range(len(keys) - 1):
            k = keys[i]
            if k not in config:
                config[k] = {}
            elif not isinstance(config[k], dict):
                config[k] = {}
            config = config[k]

        # 设置最后一个键的值
        config[keys[-1]] = value
        return True

    def save(self):
        """
        保存配置到文件

        Returns:
            是否保存成功
        """
        try:
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(self.config, f, indent=2, ensure_ascii=False)
            self.logger.info(f"已保存配置到文件: {self.config_file}")
            return True
        except Exception as e:
            self.logger.error(f"保存配置到文件失败: {str(e)}")
            return False

    def get_minio_config(self):
        """
        获取MinIO配置

        Returns:
            MinIO配置字典
        """
        return self.get("minio", {})

    def get_nacos_config(self):
        """
        获取Nacos配置

        Returns:
            Nacos配置字典
        """
        return self.get("nacos", {})
